// components/Filelist/index.js
import { request, canDownload,Encrypt,canEditor } from '../../utils/util'
const { $Message } = require('../../dist/base/index');
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    fileId: { //文件的id
      type: Number,
      value: ""
    },
    key: {   //文件夹的key
      type: Number,
      value: ""
    },
    name: {     //文件的名称title
      type: String,
      value: ""
    },
    type: {     //数据的类型 types
      type: String,
      value: ""
    },
    path: {    //应该是没用的
      type: String,
      value: "1"
    },
    time: {   //创建时间creat_time
      type: String,
      value: ''
    },
    size: {   //文件大小size 单位b
      type: String,
      value: ""
    },
    uploadMan: { //上传者
      type: String,
      value: ""
    },
    classifyType: { //文件自哪个空间来的
      type: String,
      value: ""
    },
    isNeedAction: {  //是否展示功能（三个点） 默认均需要
      type: Boolean,
      value: true
    },
    cId: {
      type: Number
    }, //取消收藏用的id
    isCollect: {
      type: Number
    },//收藏的状态
    optionType: { //移动复制时传进来的操作类型
      type: String
    },
    backPageClassify: {  //返回页面时从哪来的
      type: String
    },
    project: {
      type: Number
    }, //项目里的folderpage用到
    fileUuid: {    //文件的Uuid
      type: String
    },
    homeType: {   //来源类型
      type: String
    },
    version: {//版本号
      type: String
    },
    old_doc: { //历史版本
      type: Array
    },
    abstract: {  //描述
      type: String,
      value: null
    },
    catalog: { //父级目录
      type: Number
    },
    file_id: { //上传新版本时用到的file_id
      type: String
    },
    isOrgRoot: {
      type: Boolean,
      value: false
    }, //是否为根目录
    collectProject: {
      type: Number,
      value: null
    },
    is_gzh: {
      type: Boolean,
      value: false
    },
    
  },

  /**
   * 组件的初始数据
   */
  data: {
    visibleOptions: false,
    actionsOptionsUncollect: [//企业里未收藏的
      {
        name: "移动"
      },
      {
        name: "复制"
      },
      {
        name: "收藏"
      },
      {
        name: "下载"
      },
      {
        name: '重命名'
      },
      {
        name:'在线编辑'
      },
      {
        name: '版本控制'
      },
      {
        name: '分享',
        icon: 'share',

      },
      {
        name: '删除',
        color: 'red'
      }
    ],
    actionsOptionsCollected: [//企业里已收藏的
      {
        name: "移动"
      },
      {
        name: "复制"
      },
      {
        name: "已收藏"
      },
      {
        name: "下载"
      },
      {
        name: '重命名'
      },
      {
        name:'在线编辑'
      },
      {
        name: '版本控制'
      },
      {
        name: '分享',
        icon: 'share',

      },
      {
        name: '删除',
        color: 'red'
      }
    ],
    actionsForCancel: [ //我的收藏里别人的文件
      {
        name: '取消收藏',
      },
      {
        name: '分享',
        icon: 'share',

      },
    ],

    actionsForOwnerCollect: [ //我的收藏里自己新建的
      {
        name: '重命名',
      },
      {
        name: '分享',
        icon: 'share',
        // openType: 'share'
      },
      {
        name: '删除',
        color: 'red'
      },
    ],
    visibleDelete: false,
    actionsDelete: [
      {
        name: '取消'
      },
      {
        name: '删除',
        color: '#ed3f14',
        loading: false
      }
    ],
    

  },
  /**
   *   在组件实例进入页面节点树时执行
   * 是公众号文章时，操作栏减少一个版本控制
   */
  attached: function () {
    if (this.properties.isCollect === 0) {
      if (this.properties.is_gzh === true) {
        const action = this.data.actionsOptionsUncollect
        action.splice(6, 1)
        this.setData({
          ...this.data,
          actionsOptionsUncollect: action
        })
      }
      if (this.properties.type === 'folder') {
        const action = this.data.actionsOptionsUncollect
        action.splice(3,1)
        action.splice(4,3)
        this.setData({
          ...this.data,
          actionsOptionsUncollect: action
        })
      }
    }
    if (this.properties.isCollect !== 0) {
      if (this.properties.is_gzh === true) {
        const action = this.data.actionsOptionsCollected
        action.splice(6, 1)
        this.setData({
          ...this.data,
          actionsOptionsCollected: action
        })
      }
      if (this.properties.type === 'folder') {
        const action = this.data.actionsOptionsUncollect
        action.splice(3,1)
        action.splice(4,3)
        this.setData({
          ...this.data,
          actionsOptionsUncollect: action
        })
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 孙子调用祖方法
     */
    getFileList() {
      this.triggerEvent("getFileList")
    },
    /**
     * 打开上啦菜单
     */
    handleOpen1() {

      this.setData({
        visibleOptions: true
      });
    },
    /**
     * 关闭上啦菜单
     */
    handleCancel1() {
      this.setData({
        visibleOptions: false
      });
    },
    /**
     * 上啦框里的各个事件(企业和个人)
     * @param {}} param0 
     */
    handleClickOptions({ detail }) {
      let index = detail.index + 1;
      
      if (this.properties.is_gzh) {//是公众号文章时，点击的加一
        if (index >= 7) {
          index = index + 1
        }
      }
      if(this.properties.type === 'folder'){//控制文件夹不显示
           if(index === 4){
             index = 5
           }else if(index === 5){
             index = 9
           }
          
      } 
      const navigateTitle = "选择路径"
      const classifyType = "collect" //给收藏用的
      let fileKey = ""; //给收藏用的
      let type = "";  //给收藏用的
      let mFileKey = "";//给移动和复制用
      let mType = ""; //给移动和复制用

      if (this.properties.type === "folder") {
        fileKey = this.properties.key
        type = "catalog_org"
        mFileKey = this.properties.key
        mType = "source_catalog"
      } else {
        fileKey = this.properties.fileId
        type = "doc"
        mFileKey = this.properties.fileId
        mType = "source_doc"
      }
      app.globalData.collect.fileKey = fileKey
      app.globalData.collect.type = type
      app.globalData.moveAndCopy.fileKey = mFileKey
      app.globalData.moveAndCopy.type = mType
      switch (index) {
        case 1:
          this.handleCancel1();
          wx.navigateTo({
            url: `/pages/components/MoveAndCopy/moveAndCopy?title=移动到文件夹&type=移动&backPageClassify=${this.properties.classifyType}`,
          })
          break;
        case 2:
          this.handleCancel1();
          wx.navigateTo({
            url: `/pages/components/MoveAndCopy/moveAndCopy?title=复制到文件夹&type=复制&backPageClassify=${this.properties.classifyType}`,
          })
          break;
        case 3:
          if (this.properties.isCollect === 0) {
            this.handleCancel1();
            wx.navigateTo({
              url: `/pages/components/Collect/collect?classifyType=${classifyType}&navigateTitle=${navigateTitle}&backPageClassify=${this.properties.classifyType}`,
              fail: res => {

              }
            })
            break;
          } else {
            this.handleCancel1();
            $Message({
              content: '请至我的收藏进行管理',
              type: 'warning'
            })
            break;
          }
        case 4:
          if (this.properties.type === "folder") {
            wx.showToast({
              title: '文件夹类型暂不支持下载',
              icon: 'none'
            })
          } else {
            app.globalData.isNeedOnshow = false
            const isAllowDownload = canDownload(this.properties.type)
            const fileName = this.properties.name
            const allowImage = ["png","jeg","jpeg"]
            const type = this.properties.type
            this.handleCancel1();
            if (isAllowDownload) {
              const param = {
                file_hash: this.properties.fileUuid,
                type:'download'
              }
              request("POST", "/api/upload/doc/download/", param)
                .then(res => {
                  if (res.statusCode === 200) {
                    $Message({
                      content: '开始下载',
                    })
                    const downloadTask = wx.downloadFile({
                      url: res.data.url, 
                      filePath:wx.env.USER_DATA_PATH + "/" + fileName,
                      success(res) {
                       
                        if(allowImage.indexOf(type) !== -1){
                          wx.previewImage({
                            urls:[res.filePath],
                            showMenu:true,
                            success: function (res) {
                              console.log('打开文档成功')
                            },
                            fail: res => {
                              console.log(res)
                            }
                          })
                        }else{
                          wx.openDocument({
                            filePath: res.filePath,
                            showMenu: true,
                            fileType: type,
                            success: function (res) {
                              console.log('打开文档成功')
                            },
                            fail: res => {
                              console.log(res)
                            }
                          })
                        }
                        

                      },
                      fail: res => {
                        console.log(res)
                      }

                    })
                    downloadTask.onProgressUpdate((res) => {
                      $Message({
                        content: '正在下载' + res.progress + '%',
                      })
                      if (res.progress === 100) {
                        $Message({
                          content: '下载成功,正在打开',
                          type: 'success',

                        })
                      }
                    })

                  } else if (res.statusCode === 430) {
                    wx.showToast({
                      title: res.data.detail,
                      icon: "none"
                    })
                  } else {
                    wx.showToast({
                      title: '服务器异常，请联系系统管理员',
                      icon: 'none'
                    })
                  }
                })
            } else {
              wx.showToast({
                title: '该文件类型暂不支持下载，请至web端进行下载',
                icon: 'none',
                duration: 1500
              })
            }

          }
          break;
        case 5:
          const num = this.properties.key || this.properties.fileId
          wx.navigateTo({
            url: `/pages/components/Rename/Rename?type=${this.properties.type}&num=${num}&classifyType=${this.properties.classifyType}&title=${this.properties.name}&project=${this.properties.project}`,
          })
          this.handleCancel1();

          break;
        case 6:
          //在线编辑
          const isOk = canEditor(this.properties.type)
          this.handleCancel1();
          if(isOk){
            app.globalData.isNeedOnshow = false
            const that = this
            const id = wx.getStorageSync('userInfo').id
            const name = wx.getStorageSync('userInfo').first_name
            const param = {
              file_hash: this.properties.fileUuid,
            }
            request("POST","/api/upload/doc/download/", param)
            .then(res =>{
              if(res.statusCode === 200){
                const param1 = {
                    id:id,
                    name:name,
                    uuid:that.properties.fileUuid,
                    url:res.data.url,
                    file_name:that.properties.name,
                    renderType:"mobile"
                }
                const newParam = Encrypt(JSON.stringify(param1))
                wx.navigateTo({
                  url: `/pages/webView/editor/editor?param=${newParam}`,
                })
              }
            })
          }else{
            wx.showToast({
              title: '该类型暂不支持在线编辑',
              icon:"none",
              duration:1500
            })
          }
          
          break;
        case 7:
          if (this.properties.type === "folder") {
            wx.showToast({
              title: '文件夹暂不支持版本控制',
              icon: "none"
            })
          } else {
            this.handleCancel1()
            const data = {
              id: this.properties.fileId,
              name: this.properties.name,
              type: this.properties.type,
              size: this.properties.size,
              uploadMan: this.properties.uploadMan,
              time: this.properties.time,
              version: this.properties.version,
              abstract: this.properties.abstract,
              old_doc: this.properties.old_doc,
              catalog: this.properties.catalog,
              file_id: this.properties.file_id,
              classifyType:this.properties.classifyType
            }
            wx.navigateTo({
              url: `/pages/components/Version/version?data=${JSON.stringify(data)}`,
            })
          }
          break;
        case 8:

          if (this.properties.type === "folder") {
            wx.showToast({
              title: '文件夹暂不支持分享',
              icon: "none"
            })
          } else {
            app.globalData.isNeedOnshow = false
            this.handleCancel1()
            wx.navigateTo({
              url: `/pages/components/Share/share?type=${this.properties.type}&name=${this.properties.name}&uuid=${this.properties.fileUuid}`,
            })
          }

          break;
        case 9:
          this.setData({
            ...this.data,
            visibleDelete: true
          });
          break;
        default:
          break;
      }

    },
    /**
     * 上拉框里的事件（收藏里的除cfolde以外的文件）
     * @param {} param0 
     */
    handleClickItemOptionsForCancel({ detail }) {
      const that = this
      const index = detail.index + 1;

      switch (index) {
        case 1:
          //取消收藏
          if (this.properties.type == "folder") {
            request("DELETE", `/api/service/collection/${this.properties.cId}/`).then(res => {
              if (res.statusCode == 200) {
                $Message({
                  content: '取消收藏成功！',
                  type: 'success'
                });
                that.setData({
                  ...that.data,
                  visibleOptions: false
                })
                that.triggerEvent("getFileList")

              }
            })
          } else {
            request("DELETE", `/api/service/collection/${this.properties.cId}/`).then(res => {
              if (res.statusCode == 200) {
                $Message({
                  content: '取消收藏成功！',
                  type: 'success'
                });
                that.setData({
                  ...that.data,
                  visibleOptions: false
                })
                that.triggerEvent("getFileList")

              }
            })
          }
          break;

        case 2:

          if (this.properties.type === "folder") {
            wx.showToast({
              title: '文件夹暂不支持分享',
              icon: "none"
            })
          } else {
            this.handleCancel1()
            wx.navigateTo({
              url: `/pages/components/Share/share?type=${this.properties.type}&name=${this.properties.name}&uuid=${this.properties.fileUuid}`,
            })
          }
          break;
        default:
          break;
      }

    },
    /**
     * 上啦框里的各个事件(暂时保留 没用 )
     * @param {}} param0 
     */
    handleClickItem3({ detail }) {
      const index = detail.index + 1;
      const navigateTitle = "选择路径"
      const classifyType = "collect"
      let fileKey = "";
      let type = "";
      if (this.properties.type === "folder") {
        fileKey = this.properties.key
        type = "catalog_org"
      } else {
        fileKey = this.properties.fileId
        type = "doc"
      }
      app.globalData.collect.fileKey = fileKey
      app.globalData.collect.type = type
      switch (index) {
        case 1:
          this.handleCancel1();
          wx.navigateTo({
            url: `/pages/components/Collect/collect?classifyType=${classifyType}&navigateTitle=${navigateTitle}`,
            fail: res => {

            }
          })
          break;
        case 2:
          const num = this.properties.key || this.properties.fileId
          wx.navigateTo({
            url: `/pages/components/Rename/Rename?type=${this.properties.type}&num=${num}&classifyType=${this.properties.classifyType}&title=${this.properties.name}`,
          })
          this.handleCancel1();

          break;
        case 3:

          break;
        case 4:
          this.setData({
            ...this.data,
            visibleDelete: true
          });
          break;
        default:
          break;
      }

    },
    /**
     * 我的收藏里可以删除的菜单
     * @param {*} param0 
     */
    handleClickItemOptionsForDelete({ detail }) {
      const index = detail.index + 1;

      switch (index) {
        case 1:
          const num = this.properties.key || this.properties.fileId
          wx.navigateTo({
            url: `/pages/components/Rename/Rename?type=${this.properties.type}&num=${num}&classifyType=${this.properties.classifyType}&title=${this.properties.name}`,
          })
          this.handleCancel1();
          break;
        case 2:
          wx.showToast({
            title: '文件夹暂不支持分享',
            icon: "none"
          })
          this.handleCancel1();

          break;
        case 3:
          this.setData({
            ...this.data,
            visibleDelete: true
          });
          break;
        case 4:

          break;
        default:
          break;
      }
    },
    /**
     * 点击文件事件
     */
    handlePriview() {
      //用来区分点击以后进入到的新页面
      if (this.properties.isNeedAction === false) {//不需要按钮的时候是移动和收藏在调用和企业根在调用
        if (this.properties.isOrgRoot === true) { //控制企业更目录的层
          wx.navigateTo({
            url: `/pages/folderpage/folderpage?name=${this.properties.name}&key=${this.properties.key}&classifyType=${this.properties.classifyType}`,
          })
        } else {
          if (this.properties.type == "folder" || this.properties.type === "cfolder") {
            if (this.properties.optionType === "移动" || this.properties.optionType === "复制") {
              wx.navigateTo({
                url: `/pages/components/MoveAndCopy/moveAndCopy2/moveAndCopy2?classifyType=${this.properties.classifyType}&type=${this.properties.optionType}&key=${this.properties.key}&backPageClassify=${this.properties.backPageClassify}&id=${this.properties.project}`,
              })
            } else {
              wx.navigateTo({
                url: `/pages/components/Collect/collect?key=${this.properties.key}&classifyType=${this.properties.classifyType}&backPageClassify=${this.properties.backPageClassify}`,
              })
            }

          }
        }


      } else {
        if (this.properties.type == "folder" || this.properties.type === "cfolder") {
          if (this.properties.project) {

            wx.navigateTo({
              url: `/pages/tabBar/project/components/projectFolderpage/index?name=${this.properties.name}&key=${this.properties.key}&classifyType=${this.properties.classifyType}&project=${this.properties.project}`,
            })
          } else {
            if (this.properties.classifyType === "user" || this.properties.classifyType === "org") {
              wx.navigateTo({
                url: `/pages/folderpage/folderpage?name=${this.properties.name}&key=${this.properties.key}&classifyType=${this.properties.classifyType}`,
              })
            } else {
              wx.navigateTo({
                url: `/pages/folderpage/folderpage?name=${this.properties.name}&key=${this.properties.key}&classifyType=${this.properties.classifyType}&homeType=${this.properties.homeType}&isNeedAdd=false&collectProject=${this.properties.collectProject}`,
              })
            }


          }


        } else {
          const noPreview = wx.getStorageSync('no_preview')
          let isNoPreview = false
          noPreview.forEach(item => {
            if (this.properties.type === item.name) {
              isNoPreview = true
              wx.showToast({
                title: '该类型不支持预览',
                icon: 'none'
              })
              return
            }
          })
          if (!isNoPreview) {
            app.globalData.isNeedOnshow = false //设置返回后不需要调用Onshow
            const param = {
              file_hash: this.properties.fileUuid
            }
            request("POST", "/api/upload/doc/preview/", param, "", true)
              .then(res => {
                if (res.statusCode === 200) {
                  wx.navigateTo({
                    url: `/pages/webView/preview/preview?url=${encodeURIComponent(res.data.url)}`,
                  })
                }
              })
          }
        }

        // wx.navigateTo({
        //  url:'../../pages/out/out.wxml', //
        //  success:function() {

        //  },  //成功后的回调；
        //  fail:function() { },   //失败后的回调；
        //  complete:function() { }  //结束后的回调(成功，失败都会执行)
        // })
      }

    },
    /**
   * 删除
   */
    delete: function ({ detail }) {

      const that = this
      if (this.properties.type === "folder" || this.properties.type == "cfolder") {
        if (detail.index === 0) {
          this.setData({
            ...this.data,
            visibleDelete: false
          });
        } else {

          const action = [...this.data.actionsDelete];
          action[1].loading = true;
          this.setData({
            ...this.data,
            actionsDelete: action
          });
          const param = {
            deleteid: [this.properties.key]
          }
          request("DELETE", `/api/service/catalog/multiple_delete/`, param)
            .then(res => {
              if (res.statusCode === 427) {
                action[1].loading = false;
                that.handleCancel1();
                that.setData({
                  ...that.data,
                  visibleDelete: false,
                  actionsDelete: action
                });
              }
              if (res.statusCode === 200) {
                action[1].loading = false;
                that.handleCancel1();
                that.setData({
                  ...that.data,
                  visibleDelete: false,
                  actionsDelete: action
                });
                this.triggerEvent("getFileList")
                $Message({
                  content: '删除成功！',
                  type: 'success'
                });
              }
            })
        }
      } else {
        if (detail.index === 0) {
          this.setData({
            ...this.data,
            visibleDelete: false
          });
        } else {
          const action = [...this.data.actionsDelete];
          action[1].loading = true;
          that.handleCancel1();
          this.setData({
            ...this.data,
            actionsDelete: action
          });

          const param = {
            deleteid: [this.properties.fileId]
          }
          request("DELETE", `/api/service/docinfo/multiple_delete/`, param)
            .then(res => {
              if (res.statusCode === 427) {
                action[1].loading = false;
                that.handleCancel1();
                that.setData({
                  ...that.data,
                  visibleDelete: false,
                  actionsDelete: action
                });
              }
              if (res.statusCode === 200) {
                action[1].loading = false;
                that.handleCancel1();
                that.setData({
                  ...that.data,
                  visibleDelete: false,
                  actionsDelete: action
                });
                this.triggerEvent("getFileList")
                $Message({
                  content: '删除成功！',
                  type: 'success'
                });
              }
            })
        }
      }
    },


    /**
     * 半屏弹窗里的事件
     * 
     */
    setHalfScreen(){
      app.globalData.halfScreen.id = this.properties.fileId || null
      app.globalData.halfScreen.key = this.properties.key || null
      app.globalData.halfScreen.type = this.properties.type
      app.globalData.halfScreen.isOrgRoot = this.properties.isOrgRoot
      this.triggerEvent("multipleChoice")
    },
    

  }
}) 